<%@ page pageEncoding="UTF-8"%>
<%@ include file="validate.jsp"%>
<%!
    /**
     *	验证客户端令牌
     */
    public  Message validateToken(Input input) {
        Message message = new Message();
        String tokenString = input.getDesc("token", "");
        int hospital = input.getInt("hospital", 0);
        if (("".equals(tokenString)) || (0 == hospital)) {
            message.setErrcode(20001);
            return message;
        }
        // 数据库查询
        List list = QBuilder.db("basedb").queryHql("from token where hospital = '" + hospital + "' and token = '" + tokenString + "'");
        if (list.size() == 0) { // 没有匹配的记录
            message.setErrcode(20004);
            return message;
        }
        // 取出数据库中token记录
        Map tokenMap = (HashMap) list.get(0);
        int status = Tools.getInt(tokenMap.get("status") + "", 2);
        if (status == 3) {
            message.setErrcode(20003);
            return message;
        }
        if (-1 == Tools.getInt(tokenMap.get("expireIn") + "", 0)) { // 微信用户
            message.setErrmsg("token验证成功");
            message.put("token", Token.fromMap(tokenMap, Token.class));
            return message;
        }
        // 延迟30秒，防止客户端没过期，传递到服务端过期了
        int expireIn = 1000 * (Tools.getInt(tokenMap.get("expireIn") + "", 0) + 20);
        Long createAt = Tools.getLong(tokenMap.get("cTime") + "", 0L);
        Long now = System.currentTimeMillis();
        if (now < (createAt + expireIn)) { // 有效
            message.setErrmsg("token验证成功");
            Token token = Token.fromMap(tokenMap, Token.class);
            // 如果用户被删除了，则强制退出
            List<User> users = QBuilder.db("basedb").queryHql("from User where status=1 and id =" + token.getUid());
            if (isEmpty(users)) {
                message.setErrcode(20004);
                return message;
            }
            message.put("token", Token.fromMap(tokenMap, Token.class));
            return message;
        } else if (now < (createAt + expireIn + 2*24*3600*1000)) { // token过期超过1小时但不超过两天
            message.setErrcode(20002);
            return message;
        } else { // token超过两天，响应token不存在，迫使客户端重新登录
            message.setErrcode(20004);
            return message;
        }
    }
%>
<%
    msg = validateToken(input);
    errcode = msg.getErrcode();
    if (0 != errcode) {
        Tools.encryptPrint(out, msg);
        return;
    }
    Token token = (Token)msg.get("token");

    msg = new Message();
    msg.put("data", new ArrayList());
    hospital = input.getInt("hospital", -1); // 医院id
    act = input.getDesc("act", "list"); // 访问类型
    parameters = input.getParameters(); // 解密后的参数
%>
